<?php
/**
 * 模特管理操作类
 * @author 王志昂
 * @create 2013-05-08 20:37:32
 */
class Business_Model
{
    protected $_modelTableInfo;

    protected $_table;

    protected static $_instance;

    public static function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new Business_Model();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $this->_modelTableInfo = Zend_Registry::get('database')->modellist;
        $this->_table = Zend_Registry::get('database')->modellist->tablename;
    }

    /**
     * 根据类型获取模特的数量
     *
     * @param int $type
     *            类型
     *            0时获得所有类型记录条数
     */
    public function getModelAmount($type)
    {
        $select = Utility_Db::getInstance()->conn()->select();
        $select->from($this->_table);
        if (!empty($type)) {
            $select->where($this->_modelTableInfo->type . '=?', $type);
        }
        $list = $select->query()->fetchAll();
        return count($list);
    }

    /**
     * 根据类型获取模特
     *
     * @param int|array $type
     *            类型
     * @param int $page
     *            页码
     * @param int $rowCount
     *            每页有多少模特
     */
    public function getModelList($type, $display = null, $page = null, $rowCount = null)
    {
        $select = Utility_Db::getInstance()
            ->conn()
            ->select()
            ->from($this->_table);
        if (!empty($type)) {
            if (!is_array($type)) {
                $select->where($this->_modelTableInfo->type . '=?', $type);
            } else {
                $len = count($type);
                for ($i = 0; $i < $len; $i++) {
                    $value = $type[$i];
                    if ($i == 0) {
                        $select->where($this->_modelTableInfo->type . '=?', $value);
                    } else {
                        $select->orWhere($this->_modelTableInfo->type . '=?', $value);
                    }
                }
            }
        }
        if ($display == 1) {
            $select->where($this->_modelTableInfo->display . '=?', $display);
        }
        if (!empty($page) && !empty($rowCount)) {
            $select->limitPage($page, $rowCount);
        }
        $select->order($this->_modelTableInfo->ctime . ' DESC');
        $list = $select->query()->fetchAll();
        return $list;
    }

    /**
     * 获取模特的详细内容
     * @param int $id
     */
    public function getModelDetails($id)
    {
        $modelDetail = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_table)
            ->where($this->_modelTableInfo->id . '=?', $id)
            ->query()
            ->fetch();
        return $modelDetail;
    }

    /**
     * 修饰模特的插入数据，加上图片的长宽比
     */
    private function _decorateModelData($data)
    {
        $pictures = unserialize($data[$this->_modelTableInfo->pictures]);
        $pictureSizes = array();
        foreach ($pictures as $picture) {
            list($width, $height) = getimagesize(PROJECT_ROOT . $picture);
            $pictureSizes[] = array(
                'width' => $width,
                'height' => $height
            );
        }
        $data[$this->_modelTableInfo->pictureSize] = serialize($pictureSizes);
        return $data;
    }
    
    /**
     * 保存模特
     * @param Array $data
     * @return boolean
     */
    public function save($data)
    {
        $data = $this->_decorateModelData($data);
        if (empty($data[$this->_modelTableInfo->id])) {
            unset($data[$this->_modelTableInfo->id]);
            $data[$this->_modelTableInfo->ctime] = date("c");
        }

        $data[$this->_modelTableInfo->mtime] = date("c");

        $db = Utility_Db::getInstance()->conn();
        try {
            $insRowNum = $db->insert($this->_table, $data);
            if ($insRowNum) {
                $rtn = array(
                    'errorcode' => 0,
                    'errormsg' => '操作成功'
                );
            } else {
                $rtn = array(
                    'errorcode' => -1,
                    'errormsg' => '数据库插入失败'
                );
            }
        } catch (Zend_Db_Exception $exp) {
            if ($exp->getCode() == 1062) {
                $modelid = $data[$this->_modelTableInfo->id];
                $where = array(
                    $this->_modelTableInfo->id . ' = ?' => $modelid
                );
                unset($data[$this->_modelTableInfo->id]);
                if (isset($data[$this->_modelTableInfo->ctime])) {
                    unset($data[$this->_modelTableInfo->ctime]);
                }
                $affectRows = $db->update($this->_table, $data, $where);
                if ($affectRows) {
                    $rtn = array(
                        'errorcode' => 0,
                        'errormsg' => '操作成功'
                    );
                } else {
                    $rtn = array(
                        'errorcode' => -1,
                        'errormsg' => '数据库更新失败'
                    );
                }
            } else {
                $rtn = array(
                    'errorcode' => -1,
                    'errormsg' => $exp->getMessage()
                );
            }
        }
        return $rtn;
    }

    /**
     * 删除指定ID的模特
     * @param Integer $id
     * @return Integer
     */
    public function delete($id)
    {
        $db = Utility_Db::getInstance()->conn();
        $where = array(
            $this->_modelTableInfo->id . ' = ?' => $id
        );
        $rows = $db->delete($this->_table, $where);
        if ($rows) {
            $rtn = array(
                'errorcode' => 0,
                'errormsg' => 'success'
            );
        } else {
            $rtn = array(
                'errorcode' => - 1,
                'errormsg' => 'failed'
            );
        }
        return $rtn;
    }

    /**
     * 根据id修改是否显示
     * @param int $id
     * @param int $displays
     * @return array
     */
    public function setDisplay($id, $displays)
    {
        $db = Utility_Db::getInstance()->conn();
        $where = array(
            $this->_modelTableInfo->id . ' = ?' => $id
        );
        $bind = array($this->_modelTableInfo->display => $displays);
        $rows = $db->update($this->_table, $bind, $where);
        if ($rows) {
            $rtn = array(
                'errorcode' => 0,
                'errormsg' => 'success'
            );
        } else {
            $rtn = array(
                'errorcode' => - 1,
                'errormsg' => 'failed'
            );
        }
        return $rtn;
    }

    public function getModelTypes()
    {
        $modelTypeTable = Zend_Registry::get('database')->modeltype;
        return Utility_Db::getInstance()
            ->conn()
            ->select()
            ->from($modelTypeTable->tablename)
            ->query()
            ->fetchAll();
    }

    public function saveModelJoin($bind)
    {
        $char = Zend_Registry::get('lang')->model->join;
    	$joinTable = Zend_Registry::get('database')->modeljoin;
    	$bind[$joinTable->ctime] = date('c');
    	try {
    		$result = Utility_Db::getInstance()
	    		->conn()
	    		->insert($joinTable->tablename, $bind);
    		if ($result) {
    			$rtn = array(
    				'errorcode' => 0,
    				'errormsg' => $char->alert4
    			);
    		} else {
    			$rtn = array(
    				'errorcode' => -1,
    				'errormsg' => $char->alert5
    			);
    		}
    	} catch (Exception $e) {
    		$rtn = array(
    			'errorcode' => $e->getCode(),
    			'errormsg' => $char->alert6
    		);
    	}
    	return $rtn;
    }

    public function getModelJoin($page = null, $rowCount = null)
    {
    	$joinTable = Zend_Registry::get('database')->modeljoin;
    	$select = Utility_Db::getInstance()
	    	->conn()
	    	->select()
	    	->from($joinTable->tablename);
    	if (!empty($page) && !empty($rowCount)) {
    		$select->limitPage($page, $rowCount);
    	}
    	$list = $select->query()->fetchAll();
    	return $list;
    }

    public function getModelJoinAmount()
    {
    	$joinTable = Zend_Registry::get('database')->modeljoin;
    	$result =  Utility_Db::getInstance()
	    	->conn()
	    	->select()
	    	->from($joinTable->tablename)
    		->query()
    		->fetchAll();
    	return count($result);
    }
    
    public function getModelJoinById($id)
    {
        $joinTable = Zend_Registry::get('database')->modeljoin;
        $result =  Utility_Db::getInstance()
            ->conn()
            ->select()
            ->from($joinTable->tablename)
            ->where($joinTable->id . '=?', $id)
            ->query()
            ->fetch();
        return $result;
    }
    
    /**
     * 删除指定ID的模特加盟信息
     * @param Integer $id
     * @return Integer
     */
    public function deleteModelJoin($id)
    {
        $db = Utility_Db::getInstance()->conn();
        $joinTable = Zend_Registry::get('database')->modeljoin;
        $where = array(
            $joinTable->id . ' = ?' => $id
        );
        $rows = $db->delete($joinTable->tablename, $where);
        if ($rows) {
            $rtn = array(
                'errorcode' => 0,
                'errormsg' => 'success'
            );
        } else {
            $rtn = array(
                'errorcode' => - 1,
                'errormsg' => 'failed'
            );
        }
        return $rtn;
    }
}